package cn.edu.whu.irlab.web;

import cn.edu.whu.irlab.model.Topic;
import cn.edu.whu.irlab.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Roger on 2016/7/29.
 */
@Controller
@RequestMapping("/topic")
public class TopicManageController {

    @Autowired
    private TopicService topicService;

    @RequestMapping(method = RequestMethod.GET)
    public String topic(Model model){
        List<Topic> topics = topicService.selectRootTopic();
        model.addAttribute("topics", topics);
        return "topic/topic";
    }

    @RequestMapping(value = "/{topicId}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTopicTree(@PathVariable Integer topicId){
        long start = System.nanoTime();
        Map<String, Object> map = new HashMap<>();
        Topic topic = topicService.selectByPrimaryKey(topicId);
        List<Topic> parentTopics = topicService.recurseParentTopic(topicId);
        map.put("parentTopics", parentTopics);

        List<Topic> childTopics = topicService.selectChildTopic(topicId);
        map.put("childTopics", childTopics);
        long end = System.nanoTime();
        System.out.println(end - start);
        return map;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createTopic(@RequestParam(name = "name") String name,
                              @RequestParam(name = "parentId", defaultValue = "0") Integer parentId){
        Topic topic = new Topic();
        topic.setName(name);
        topic.setParentId(parentId);
        topic.setCreateTime(new Date());
        topicService.insertSelective(topic);
        return "";
    }


    @RequestMapping(value = "/child/{topicId}", method = RequestMethod.GET)
    @ResponseBody
    public List<Topic> getChild(@PathVariable Integer topicId){
        return topicService.selectChildTopic(topicId);
    }
}
